package v1

import (
	"time"
	"net/http"
	"hytx_media/pkg/aliyun"
	"hytx_media/pkg/app"
	"hytx_media/pkg/util"
	"hytx_media/service/sms_validate_service"

	"github.com/gin-gonic/gin"
	"github.com/Unknwon/com"
)

// 发送短信
func SMSsendVerification(c *gin.Context) {
	appG := app.Gin{c}
	phone := c.Query("phone")
	if phone == "" {
		appG.ResponseMsg(http.StatusOK, "电话不是黑正确哦", false)
		return
	}

	now := time.Now()
	code := util.SixVerificationCode()

	// 查询数据用于验证时间是否过期
	sc := sms_validate_service.SMSValidate{
		MobilePhone: phone,
	}
	smsValidateResult, err := sc.Select()

	if err == nil {
		if smsValidateResult.DeadLine.Unix() - time.Now().Unix() > 0 && smsValidateResult.DeadLine.Unix() - time.Now().Unix() < 300{
			appG.ResponseMsg(http.StatusOK, "亲，你太激动了，5分钟过后再试哟", false)
			return
		}
	}

	// 发送短信
	send, err := aliyun.SMSsend(phone, code)
	if err != nil {
		appG.ResponseMsg(http.StatusOK, "发送失败！", false)
	}

	// 当前时间加5分钟
	mm, _ := time.ParseDuration("5m")
	DeadLine := now.Add(mm)
	sType := com.StrTo(c.Query("type")).MustInt()
	s := sms_validate_service.SMSValidate{
		Type : sType,
		MobilePhone : phone,
		DeadLine : DeadLine,
		MsgCode : code,
		IsValided : 0,
		IsSended : 1,
		TempId : "SMS_117290028",
		Data : code,
		ResultInfo : send,
	}

	if err := s.Add(); err != nil {
		appG.ResponseMsg(http.StatusOK, "短信写入失败", false)
		return
	}

	appG.ResponseMsg(http.StatusOK, "发送成功！", true)
}
